package orm.infrastructure.converters;

import orm.er.AddressMock;
import orm.infrastructure.interfaces.IMockConverter;
import orm.infrastructure.interfaces.IValidable;

import java.util.Dictionary;
import java.util.Hashtable;

/**
 * Created with IntelliJ IDEA.
 * User: Awake
 * Date: 03.05.12
 * Time: 17:41
 * To change this template use File | Settings | File Templates.
 */
public class AddressConverter implements IMockConverter {

    private static final String ADDRESS_ID_FIELD = "addressID";
    private static final String PERSON_ID_FIELD = "personID";
    private static final String ADDRESS_FIELD = "address";
    private static final int ADDRESS_FIELDS_COUNT = 3;

    @Override
    public Dictionary<String, Object> toDictionary(IValidable mock) {

        AddressMock addressMock = (AddressMock) mock;
        if (addressMock.isNullable())
            throw new NullPointerException();

        Dictionary<String, Object> dictionary = new Hashtable<String, Object>(ADDRESS_FIELDS_COUNT);
        dictionary.put(ADDRESS_ID_FIELD, addressMock.getAddressID());
        dictionary.put(PERSON_ID_FIELD, addressMock.getPersonID());
        dictionary.put(ADDRESS_FIELD, addressMock.getAddress());

        return dictionary;
    }

    @Override
    public IValidable toObject(Dictionary<String, Object> dictionary) {

        if (dictionary.isEmpty())
            throw new NullPointerException();

        AddressMock addressMock = new AddressMock();

        if (dictionary.get(ADDRESS_ID_FIELD) != null) {
            addressMock.setAddressID((Integer) dictionary.get(ADDRESS_ID_FIELD));
        }
        if (dictionary.get(PERSON_ID_FIELD) != null) {
            addressMock.setPersonID((Integer) dictionary.get(PERSON_ID_FIELD));
        }
        if (dictionary.get(ADDRESS_FIELD) != null) {
            addressMock.setAddress((String) dictionary.get(ADDRESS_FIELD));
        }

        return addressMock;
    }
}
